#include "qtmlibcsv.h"
#include "libcsv/minicsv.h"

#define CSV_MAX_COLUM 1024

QTmLibCSV::QTmLibCSV(QObject *parent) : QObject(parent)
{
    pr_strFilePath = "";
}

bool QTmLibCSV::loadFile(QString strFilePath)
{
    QFile curFile(strFilePath);
    if( !curFile.exists() ){
        qDebug()<<"File is not exists."<<strFilePath;
        return false;
    }
    QByteArray bContent;
    pr_strFilePath = strFilePath;
    if( curFile.open(QIODevice::ReadOnly) ){
        bContent = curFile.readAll();
        curFile.close();
    }
    pr_listContent.clear();
    // parser
    char  *cols[CSV_MAX_COLUM];
    char  *r = bContent.data();
    size_t cols_count=0;
    int rows=0,colums=0;
    while(true){
        if(!*r){
            break;
        }
        char * next_r = NULL;
        next_r = minicsv_parse_line(r, cols, &cols_count, CSV_MAX_COLUM);
        _processList(cols, cols_count);
        if( colums < (int)cols_count ){
            colums = cols_count;
        }
        rows += 1;
        r = next_r;
    }
    // update size
    pr_maxSize = QSize(rows, colums);
    return true;
}

QString QTmLibCSV::getTextAt(int i, int j, bool *bSuccess)
{
    int nRowSize = pr_listContent.size();
    if( nRowSize <= i || nRowSize<1){
        if(bSuccess) *bSuccess=false;
        return "";
    }
    QStringList oneRow = pr_listContent[i];
    int nColumSize = oneRow.size();
    if( nColumSize <= j || nColumSize<1){
        if(bSuccess) *bSuccess=false;
        return "";
    }
    if(bSuccess) *bSuccess=true;
    return oneRow[j];
}

QStringList QTmLibCSV::getTextRow(int i, bool *bSuccess)
{
    int nRowSize = pr_listContent.size();
    if( nRowSize <= i || nRowSize<1){
        if(bSuccess) *bSuccess=false;
        return QStringList();
    }
    if(bSuccess) *bSuccess=true;
    return pr_listContent[i];
}

QStringList QTmLibCSV::getTextColum(int j, bool *bSuccess)
{
    QStringList oneColum;
    foreach (QStringList oneRow, pr_listContent) {
        int nSize = oneRow.size();
        if( nSize <= j ){
            if(bSuccess) *bSuccess = false;
            oneColum.clear();
            break;
        }
        oneColum.append(oneRow[j]);
    }
    return oneColum;
}

QSize QTmLibCSV::getContentSize()
{
    return pr_maxSize;
}

QList<QStringList> QTmLibCSV::getDataList()
{
    return pr_listContent;
}

void QTmLibCSV::_processList(char **pBuff, int nSize)
{
    QStringList oneRowList;
    for(int i=0; i<nSize; i++){
        oneRowList.append(QString::fromLocal8Bit(pBuff[i]));
    }
    pr_listContent.append(oneRowList);
}

